package com.cwj.thread.cancelthread;

/**
 * 利用线程方法 interrupt() 来标识该线程是否被中断。如果该线程被阻塞，则会在抛出 InterruptedException
 * 异常之前，清除该线程的中断状态。即调用 isInterrupted() 方法返回false.
 */
public class InterruptTest {
    public static void main(final String[] args) {

        // 使用interrupt()方法中断线程
        Runner one = new Runner();
        Thread thread = new Thread(one, "one Thread");
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis());
        thread.interrupt();

        try {
            Thread.sleep(5_000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        // 对有阻塞情况的线程尝试调用interrupt()方法
        Runner2 two = new Runner2();
        Thread thread2 = new Thread(two, "two Thread");
        thread2.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis());
        thread2.interrupt();

    }

    
    private static class Runner implements Runnable {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(Thread.currentThread().getName() + " running");
            }
            System.out.println(System.currentTimeMillis());
            System.out.println("end");
        }

    }

    private static class Runner2 implements Runnable {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(Thread.currentThread().getName() + " running");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 当捕获异常时，中断标识会被清空，导致程序一直循环，需要主动设置中断状态，跳出循环。
                    // 复杂业务要对异常情况处理，保证业务数据的正确性。
                    Thread.currentThread().interrupt();
                }
            }
            System.out.println(System.currentTimeMillis());
            System.out.println("end");
        }
        
    }
}